import dateFormat from '../../utils/dateFormat';
class NewDate extends Date{
}
NewDate.prototype.Format=dateFormat.dateFormat
const defaultState={
  ipt:'ToDoList',
  iptVal:'输入点什么吧...',
  ToDoList:[]
}
export default (state=defaultState,action)=>{
  switch(action.type){
    case 'submitIpt':{
      let newState=JSON.parse(JSON.stringify(state))
      newState.ToDoList.push({
        id:Date.now()+state.ToDoList.length,
        title:action.payload.text,
        complete:false,
        date:(new NewDate().Format("yyyy年MM月dd日hh小时mm分ss秒")),
        edit:false
      })
      window.localStorage.setItem('todoList',JSON.stringify(newState.ToDoList))
      return newState
    }
    case 'initToDo':{
      let newState=JSON.parse(JSON.stringify(state))      
      newState.ToDoList=action.data.map(
        (v,i)=>{
          v.edit=false
          return v
        }
      )
      return newState
    }
    case 'completeChange':{
      let newState=JSON.parse(JSON.stringify(state))
      let current=newState.ToDoList.find((v)=>{
        return v.id===action.payload.id
      })
      current.complete=!action.payload.complete
      window.localStorage.setItem('todoList',JSON.stringify(newState.ToDoList))
      return newState
    }
    case 'deleteToDo':{
      let newState=JSON.parse(JSON.stringify(state))
      newState.ToDoList= newState.ToDoList.filter((v)=>v.id!==action.payload.id)
      window.localStorage.setItem('todoList',JSON.stringify(newState.ToDoList))
      return newState
    }
    case 'edit':{
      var newState=JSON.parse(JSON.stringify(state))
      newState.ToDoList.forEach((current,i)=>{
       if (current.id===action.payload.id){
         current.title=action.payload.txt||current.title
         if(current.edit){
           current.edit=!current.edit
           window.localStorage.setItem('todoList',JSON.stringify(newState.ToDoList)) 
         }else{
           window.localStorage.setItem('todoList',JSON.stringify(newState.ToDoList)) 
           current.edit=!current.edit
         }
        }
      })
      return newState
    }
    case 'UPDATE_TODO_LIST':{
      const newState={...state}
      console.log(action);
      newState.ToDoList=action.payload
      window.localStorage.setItem('todoList',JSON.stringify(newState.ToDoList)) 
      return newState
    }
    default:break
  }
  return state
}